package com.hjq.controller;

import com.hjq.pojo.Article;
import com.hjq.pojo.PageBean;
import com.hjq.pojo.Result;
import com.hjq.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @PostMapping
    public Result add(@RequestBody @Validated Article article) {
        log.info("新增文章，参数为：{}", article);

        articleService.add(article);
        return Result.success();
    }

    @GetMapping
    public Result<PageBean<Article>> list(Integer pageNum,
                                          Integer pageSize,
                                          @RequestParam(required = false) Integer categoryId,
                                          @RequestParam(required = false) String state) {
        log.info("文章列表分页查询，参数为：{}，{}，{}，{}", pageNum, pageSize, categoryId, state);
        PageBean<Article> pb = articleService.list(pageNum,pageSize,categoryId,state);
        return Result.success(pb);
    }

    @PutMapping
    public Result update(@RequestBody @Validated Article article){
        log.info("更新文章，参数为：{}", article);

        // 需不需要先判断文章是否存在呢？
        articleService.update(article);
        return Result.success();
    }

    @GetMapping("/detail")
    public Result<Article> detail(Integer id){
        log.info("获取文章详情，参数为：{}", id);
        Article article = articleService.detail(id);
        return Result.success(article);
    }

    @DeleteMapping
    public Result delete(Integer id){
        log.info("删除文章，参数为：{}", id);
        articleService.delete(id);
        return Result.success();
    }
}
